<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{
    # Set the various components and helpers to use.
    public $helpers = array(
        'Js', 'Html', 'Form', 'Session', 'Select', 'Message'
    );

    public $components = array(
        'RequestHandler', 'Session','Cookie',
        'Auth' => array(
            'loginAction' => array('controller' => 'Users', 'action' => 'login'),
            'loginRedirect' => array('controller' => 'Router', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
        ),
        'ExcelPHP','Sms','Api','Message','Upload','PHPMailer'
    );

    # Vehicle Types

    # SMS Statuses
    var $sms_status = array(
        'Delivered'=>'Delivered',
        'Failed'=>'Failed'
    );


    public $application_statuses = array(
        0=>'In Complete Application',
        1=>'Submitted Application',
        2=>'Completed Application',
        3=>'Admitted',
        4=>'Admission Declined'
    );


    public $global_company = array();

    public $action_permission = array();


    function beforeFilter($validate_access_control = true)
    {
        $authUser = $user_auth = $this->Auth->user();
        $this->getMenus($authUser['group_id'],$validate_access_control);
        $this->processUserCookie();
        $this->updateUserLoginTime();
        //$this->getMessageCount();
        $this->get_credit_balance();
        $this->set(compact('authUser'));
    }

    function getMenus($group_id,$validate_access_control)
    {
        $MenuGroup = ClassRegistry::init('MenuGroup');
        $user_menus = $MenuGroup->getGroupMenus($group_id);
        if($validate_access_control){
            $this->accessControlValidation($user_menus);
        }
       // debug($user_menus);
        $this->set(compact('user_menus'));
    }

    function accessControlValidation($user_menus){
        $action = $this->params['action'];
        $controller = $this->params['controller'];
        $is_allowed = false;
        if(stristr($action, 'print_export') !== false) {//Skip for print and export functions
             return true;
        }
        if(stristr($action, 'print') !== false) {//Skip for print
            return true;
        }
        if(stristr($action, 'export') !== false) {//Skip for export
            return true;
        }
        if(stristr($action, 'import') !== false) {//Skip for export
            return true;
        }
        if(stristr($action, 'view') !== false) {//Skip for export
            return true;
        }
        if(stristr($action, 'uploads') !== false) {//Skip for export
            return true;
        }
        if(stristr($action, 'skip') !== false) {//Skip for export
            return true;
        }
        if($controller == 'Dashboard'){
            return true;
        }

        foreach($user_menus as $menu){
            if($is_allowed){
                break;
            }
            if(isset($menu['sub'])){
                foreach($menu['sub'] as $inner_um){
                    if($controller == $inner_um['controller'] && $action == $inner_um['action']){
                        $is_allowed = true;
                        $this->action_permission = explode(',',$inner_um['permission']);
                        break;
                    }
                }
            }
            else{
                if($controller == $menu['controller'] && $action == $menu['action']){
                    $is_allowed = true;
                    $this->action_permission = explode(',',$menu['permission']);
                }
            }
        }
        if(!$is_allowed){//if not allowed, redirect to Router
            $this->redirect(array('controller' => 'Router', 'action' => 'index'));
        }
    }


    function cleanInput($input) {
        $search = array(
            '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
            '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
            '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
            '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
        );
        $output = preg_replace($search, '', $input);
        return $output;
    }

    function sanitize($input) {
        //debug($input);
        if (is_array($input)) {
            $output = array();
            foreach($input as $var=>$val) {
                $output[$var] = $this->sanitize($val);
            }
        }
        else {
            if (get_magic_quotes_gpc()) {
                $input = stripslashes($input);
            }
            $input  = $this->cleanInput($input);
            $new_enough_php = function_exists("mysql_real_escape_string");//i.e. PHP >= v4.3.0
            if($new_enough_php)
            {//PHP v4.3.0 or higher
                //undo any magic quote effects so mysql_real_escape_string can do the work
                // $output = mysql_real_escape_string($input);
            }
            $output = $input;
        }
        return $output;
    }

    function updateUserLoginTime()
    {
        $authUser = $this->Auth->user();
        if($authUser){
            $User = ClassRegistry::init('User');
            $User->updateAll(
                $this->sanitize(array('User.login_update_time' => "'".date('Y-m-d H:i:s')."'")),
                $this->sanitize(array('User.id' => $authUser['id']))
            );
        }
    }

    function processUserCookie()
    {
        if($this->Auth->user()){}
        else{//If the session has expired, then read from the cookie and clear the login session and time from the db
            $user_id = $this->Cookie->read('c_user_id');
            if($user_id != null){
                $User = ClassRegistry::init('User');
                $User->updateAll(
                    //array('User.login_session' => "''",'User.login_update_time' => "''"),
                    $this->sanitize(array('User.login_session' => "''")),
                    $this->sanitize(array('User.id' => $user_id))
                );
                $this->Cookie->delete('c_user_id');
            }
        }
    }


    protected  function convertToExcel($list_headers,$param ,$filename)
    {
        ini_set("memory_limit", "512M") ;
        set_time_limit('1200');

        $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
        $cacheSettings = array( ' memoryCacheSize ' => '8MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("JA Hiring")
            ->setLastModifiedBy("JA Hiring")
            ->setTitle("Office 2007 XLSX JA Hiring Document")
            ->setSubject("Office 2007 XLSX JA Hiring Document")
            ->setDescription("JA Hiring document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("JA Hiring result file");

        // Set default font
        $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);

        $count_h = 1;
        foreach($list_headers as $header){
            $letter_h = $this->getAlphabetCharacter($count_h);
            $objPHPExcel->getActiveSheet()->setCellValue($letter_h.'1', $header);
            $count_h++;
        }
        //Bold the headers
        $letter_h = $this->getAlphabetCharacter($count_h -1);
        $objPHPExcel->getActiveSheet()->getStyle('A1:'.$letter_h.'1')->getFont()->setBold(true);

        $it = 2;
        foreach ($param as $item) {
            $count_inner = 1;
            foreach($item as $itm){
                $letter_h = $this->getAlphabetCharacter($count_inner);
                $objPHPExcel->getActiveSheet()->setCellValue($letter_h.$it, strip_tags($itm));
                $count_inner++;
            }
            $it++;
        }

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Page_1');

        $objPHPExcel->setActiveSheetIndex(0);

        return array(
            'excel_obj' => $objPHPExcel,
            'filename' => $filename
        );
    }

    function getAlphabetCharacter($index)
    {
        $alphabet = array();
        for($x = 1;$x <= 1000;$x++){
            $alphabet[$x] = $this->getNameFromNumber($x);
        }
        return $alphabet[$index];
    }

    function getNameFromNumber($num) {
        $numeric = ($num - 1) % 26;
        $letter = chr(65 + $numeric);
        $num2 = intval(($num - 1) / 26);
        if ($num2 > 0) {
            return $this->getNameFromNumber($num2) . $letter;
        } else {
            return $letter;
        }
    }

    function randomString($length)
    {
        $original_string = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'),array(time()));
        $original_string = implode("", $original_string);
        return substr(str_shuffle($original_string), 0, $length);
    }

    function convertDate($date = null, $type = 'mysql')
    {
        $res = '';
        if ($type == 'mysql') {
            $res = date("Y-m-d", strtotime($date));
        }
        elseif ($type == 'mysql_flip') {
            $res = date("d-m-Y", strtotime($date));
        }
        elseif ($type == 'ui') {
            $res = date("F d, Y", strtotime($date));
        }
        elseif ($type == 'uis') {
            $res = date("M d, Y", strtotime($date));
        }
        elseif($type == 'formal'){
            $res = date("m/d/Y", strtotime($date));
        }
        return $res;
    }

    function geTimes($in_minutes = 1)
    {
        $time_arr = array();
        $start = "00:00";
        $end = "24:59";
        $tStart = strtotime($start);
        $tEnd = strtotime($end);
        $tNow = $tStart;

        while($tNow <= $tEnd){
            $format= date("H:i",$tNow);
            $time_arr[$format] = $format;
            $tNow = strtotime('+'.$in_minutes.' minutes',$tNow);
        }
        return $time_arr;
    }


    function getDays()
    {
        $start = 1;
        $end = 31;
        $days_arr = array();
        for($start; $start<=$end; $start++){
            $days_arr[$start] = $start;
        }
        return $days_arr;
    }

    function getMonths($index = null)
    {
        $months = array('01'=>'January','02'=>'February','03'=>'March','04'=>'April','05'=>'May','06'=>'June','07'=>'July','08'=>'August','09'=>'September','10'=>'October','11'=>'November','12'=>'December');
        if($index){
            return $months[$index];
        }
        else{
            return $months;
        }
    }

    function getYears($start = 2012, $end = 'CURRENT YEAR')
    {
        if($end == 'CURRENT YEAR' ){
            $end = date('Y');
        }
        $start = (int)$start;
        $end = (int)$end;
        $years_arr = array();
        for($start; $start<=$end; $start++){
            $years_arr[$start] = $start;
        }

        return $years_arr;
    }

    function count_time_between_dates($smaller_date, $bigger_date,$count_type='months')
    {
        $d1 = strtotime($smaller_date); //Smaller
        $d2 = strtotime($bigger_date); //Bigger
        $min_date = min($d1, $d2);
        $max_date = max($d1, $d2);
        $i = 0;
        $type = "+1 month";
        if($count_type == 'hours'){
            $type = "+1 hours";
        }
        elseif($count_type == 'days'){
            $type = "+1 day";
        }
        elseif($count_type == 'weeks'){
            $type = "+1 week";
        }
        elseif($count_type == 'years'){
            $type = "+1 year";
        }
        while (($min_date = strtotime($type, $min_date)) <= $max_date) {
            $i++;
        }
        return $i;
    }


    function formatNumber($value = 0, $type = 'number', $decimal_place = 2)
    {
        if ($type == 'money') {
            $num = number_format($value, $decimal_place, '.', ',');
        } else {
            $num = number_format($value, $decimal_place, '.', '');
        }

        return $num;
    }


    function __add_ordinal_suffix($num)
    {
        $last = substr($num, -1);
        if (strlen($num) < 2) {
            $next_to_last = 0;
        } else {
            $next_to_last = substr($num, -2);
        }
        if ($next_to_last >= 10 && $next_to_last < 20) {
            $suff = "th";
        } else
            if ($last == 1) {
                $suff = "st";
            } else
                if ($last == 2) {
                    $suff = "nd";
                } else
                    if ($last == 3) {
                        $suff = "rd";
                    } else {
                        $suff = "th";
                    }

        return number_format($num) . $suff;
    }

    function getMessageCount()
    {
        $authUser = $this->Auth->user();
        $MessageReciever = ClassRegistry::init('MessageReciever');
        $user_inbox = $MessageReciever->find('count',array(
            'conditions'=>array('MessageReciever.user_id'=>$authUser['id'], 'MessageReciever.msg_status'=>'unread','MessageReciever.trash'=>'n'),
            'recursive'=>-1
        ));
        $this->set(compact('user_inbox'));
        return $user_inbox;
    }


    function get_credit_balance(){
        $authUser = $this->Auth->user();
        $ModelObj = ClassRegistry::init('User');
        $credit_balance  = $ModelObj->getCreditBal($authUser['id']);
        $this->set(compact('credit_balance'));
        return $credit_balance;
    }


    function getWeekDates()
    {
        $today = date('Y-m-d');
        //w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
        $dates_arr = array();
        $day_of_week = intval(date("w"));
        $dates_arr[$day_of_week] = $today;
        $start = $day_of_week - 1;
        $reduce = 1;
        for ($x = $start; $x >= 0; $x--) {
            $today = date('Y-m-d', strtotime("-$reduce day"));
            $dates_arr[$x] = $today;
            $reduce++;
        }
        return $dates_arr;
    }


    function send_message($params,$plist=null){
        $loggedUser = $this->Auth->user();
        $user_id = $loggedUser['id'];

        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        $User = ClassRegistry::init('User');
        $Message = ClassRegistry::init('Message');
        $list = array();
        //Build the Message receivers if any
        if(isset($params['Message']['to'])){
            $tos = $params['Message']['to'];
            $usernames = explode(',',$tos);
            $find_list = array();
            foreach($usernames as $usr){
                $find_list[] = trim($usr);
            }
            $find_list = array_unique($find_list);
            $list = $User->find('list', array(
                'fields'=>array('User.id'),
                'conditions' => array('User.username' => $find_list),
                'recursive' => -1
            ));
        }
        elseif($plist){
            $list = $plist;
        }

        if(!$list){
            return array('code' => 1, 'mesg' => __('Reciepient(s) Not Found'));
        }

        $receivers = array('MessageReciever'=>array());
        foreach($list as $user){
            $receivers['MessageReciever'][] = array(
                'user_id'=>$user
            );
        }
        $params['MessageReciever'] = $receivers['MessageReciever'];

        $save = $Message->saveAll($this->sanitize($params));

        # save the data
        if ($save) {
            //Save to address book
            return array('code' => 0, 'mesg' => __('Message Sent'));
        }
        else {
            return array('code' => 1, 'mesg' => __('Message Not Sent'));
        }
    }


    function __padZero($val,$pad,$pad_type){
        $zeros = '';
        $new_num = 0;
        for($x=1; $x <= $pad; $x++){
            $zeros .= '0';
        }
        if($pad_type == 'pre_fix'){
            $new_num = $zeros.$val;
        }
        else{
            $new_num = $val.$zeros;
        }
        return $new_num;
    }

    function prePadZero($val,$pad=0){
        return $this->__padZero($val,$pad,'pre_fix');
    }

    function postPadZero($val,$pad=0){
        return $this->__padZero($val,$pad,'post_fix');
    }


    function my_debug($data){
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }

    function format_mobile($country_code,$fon_number){
        $count = count($fon_number);
        //if($count == 10){
            $fon = substr($fon_number, 1);
       /* }
        else{
            $fon = $fon_number;
        }*/

        $number = $country_code.$fon;
        return $number;
    }


    function get_sms_cost($sms_txt,$local_count,$inter_count){
        $Config = ClassRegistry::init('Config');

        $local_unit_cost = $Config->getValueByKey('local_sms_per_unit_cost');
        if(empty($local_unit_cost)){
            $local_unit_cost = 1;
        }
        $inter_unit_cost = $Config->getValueByKey('international_sms_per_unit_cost');
        if(empty($inter_unit_cost)){
            $inter_unit_cost = 3;
        }
        $per_count = $Config->getValueByKey('sms_per_unit_count');
        if(empty($per_count)){
            $per_count = 160;
        }

        $local_unit_cost = doubleval($local_unit_cost);
        $inter_unit_cost = doubleval($inter_unit_cost);
        $per_count = intval($per_count);
        $txt_count = strlen($sms_txt);
        $messages_count = 0;
        $calc = true;
        while ($calc) {
            if ($txt_count > $per_count) {
                $txt_count = $txt_count - $per_count;
                $messages_count++;
                $calc = true;
            }
            else {
                $txt_count = $txt_count - $per_count;
                $messages_count++;
                $calc = false;
            }
        }

        $total_cost_sms = (($local_unit_cost * $messages_count) * $local_count) + (($inter_unit_cost * $messages_count) * $inter_count);

        return $total_cost_sms;

    }

}
